import React, { useMemo } from "react";
import { ChunkMessage } from "../../../src/model/types";
import { wrapMessages } from "../../../src/model/helper";
import styled from "styled-components";
import { useRemarkSync } from 'react-remark';
// import remarkGfm from 'remark-gfm';
// import rehypeSlug from 'rehype-slug';
import rehypeHighlight, { Options } from'rehype-highlight';
import { HighlightjsParam } from "../../../src/store/types";

interface ChatChunkItemProps {
	content: string;
	theme: string;
}


const StyledPre = styled.pre<{ theme: any }>`
	background-color: rgba(0,0,0,0.15);
	padding: 10px 10px;
	border-radius: 5px;

	& .hljs {
		background-color: transparent;
	}

	${(props) => props.theme}
`
export const ChatChunkItem = React.memo(function(props: ChatChunkItemProps) {

	const reactContent = useRemarkSync(props.content, {
		// remarkPlugins: [remarkGfm],
		remarkToRehypeOptions: { allowDangerousHtml: true },
		rehypePlugins: [
			[rehypeHighlight as any, { ignoreMissing: true } as Options],
			// [rehypeSlug],
		],
		rehypeReactOptions: {
			components: {
				pre: ({ children, ...preProps }: any) => {
					return (
						<StyledPre {...preProps} theme={props.theme}>
							{children}
						</StyledPre>
					)
				},
			},
		}
	});
  return reactContent;
})

interface ChatChunkBoxProps {
  chunks?: ChunkMessage[];
	highlightjs?: HighlightjsParam;
}

const BoxWrap = styled.div`
margin-top: 10px;
margin-bottom: 10px;
`

interface ToolCallsChunkItemProps {
	tool_calls: ChunkMessage['tool_calls']
}

const ToolCallsChunkItem = React.memo((props: ToolCallsChunkItemProps) => {
	const tool_calls = useMemo(() => {
		console.log('工具调用', props.tool_calls)
		props.tool_calls?.forEach((item) => {
			if(item.function && item.function.name && !item.function.args) {
				let args = {}
				try {
					args = JSON.parse(item.function.arguments ?? '')
				} catch (error) {
					console.log(error)
				}
				item.function.args = args;
			}
		})
		return props.tool_calls ?? [];
	}, [props.tool_calls])
	return (
		<div>
			{tool_calls.map((item, index) => {
				return (
					<div key={index}>
						<div className="tool-calls-item">
						 <div className="name">{item.id}</div>
						 <div className="content">正在解析工具调用...</div>
						 <div className="content">{JSON.stringify(item)}</div>
						</div>	
					</div>
				)
			})}	
		</div>
	)
})

export default function ChatChunkBox(props: ChatChunkBoxProps) {
	const chunks = props.chunks;
	const newChunks = React.useMemo(() => wrapMessages(chunks ?? []), [chunks]) ;

	return (
		<>
			<BoxWrap>
				{newChunks.map((item, index) => {
					if(item.type === 'text') {
						return (<ChatChunkItem content={item.content??''} key={index} theme={props.highlightjs?.content ?? ""} />)
					}
					if(item.type === 'tool_calls') {
						return (
							<ToolCallsChunkItem key={index} tool_calls={item.tool_calls} />
						)
					}
				})}
			</BoxWrap>
		</>
	)
}